<template>
  <div class="common-wrapper">
    <div class="common-title">历史数据查询</div>
    <div class="common-main">
      <el-form
        ref="search"
        class="common-search"
        :inline="true"
        :rules="searchRules"
        :model="search"
        :show-message="false"
      >
        <el-form-item>
          <el-select
            v-model="search.org"
            placeholder="选择组织"
            size="small"
            clearable
          >
            <el-option
              v-for="(item, index) in orgOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.cj"
            placeholder="选择车间"
            size="small"
            clearable
          >
            <el-option
              v-for="(item, index) in cjOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.gongxu"
            placeholder="选择工序"
            size="small"
            clearable
            @change="changeGX"
          >
            <el-option
              v-for="(item, index) in gxOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="params">
          <el-cascader
            v-model="search.params"
            ref="cascader"
            placeholder="选择参数类型"
            size="small"
            :options="options"
            :props="cascaderProps"
            style="width: 240px"
            collapse-tags
            
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.devSn"
            placeholder="选择机台"
            size="small"
            multiple
            clearable
            class="mul-selection"
            popper-class="mul-select"
            
            collapse-tags
          >
            <el-option
              v-for="(item, index) in equipOption"
              :key="index"
              :label="search.gongxu + item.key_value + '号'"
              :value="item.key_value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="startTime">
          <el-date-picker
            size="small"
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="btn-list">
          <el-button type="primary" size="small" @click="searchNow"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="common-table" ref="chartTable">
        <el-table
          :data="tableData"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <el-table-column label="序号" width="55" align="center">
            <template slot-scope="{ row, column, $index }">
              {{ parseInt($index) + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="org" label="组织" align="center" />
          <el-table-column prop="cj" label="车间" align="center" />
          <!-- <el-table-column prop="gongxu" label="工序" align="center" /> -->
          <el-table-column prop="devSn" label="设备编号" align="center" />
          <el-table-column
            prop="time"
            width="160"
            label="时间"
            align="center"
          />
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :label="item.label"
            align="center"
          >
            <template v-for="(column, i) in item.children">
              <el-table-column
                v-if="column.value == 'llxs'"
                :prop="column.value"
                :label="column.label"
                :key="i"
                align="center"
                width="100"
                :formatter="llxsFilter"
              />
              <el-table-column
                v-else
                :prop="column.value"
                :label="column.label"
                :key="i"
                align="center"
                width="100"
              />
            </template>
          </el-table-column>
          <el-table-column prop="bc" label="班次" align="center">
          </el-table-column>
        </el-table>
      </div>
      <div class="common-pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :page-size="search.pageSize"
          :current-page.sync="search.current"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSysDict,
  getSysDictByName,
  getParams1,
  getParams2
} from '@/api/common';
import { getHistoryTrackData } from '@/api/production';
export default {
  data() {
    return {
      tableHeight: 200,
      time: [],
      search: {
        startTime: '',
        cj: '五纺',
        endTime: '',
        gongxu: '',
        devSn: [],
        org: '恒源',
        params: [],
        size: 10,
        current: 1
      },
      searchRules: {
        params: [
          { required: true, message: '请选择参数！', trigger: 'change' }
        ],
        devSn: [{ required: true, message: '请选择车台！', trigger: 'change' }],
        startTime: [
          { required: true, message: '请选择时间！', trigger: 'change' }
        ]
      },
      cascaderProps: {
        lazy: true,
        multiple: true,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          if (node.level) {
            let form = {
              gongxu: node.data.gongxu,
              cs_type: node.data.cs_type
            };
            const { data } = await getParams2(form);
            data.map(item => {
              item.label = item['cs_name'];
              item.value = item['cs'];
              item.leaf = true;
            });
            resolve(data);
          }
        }
      },
      options: [],
      // 图表部分
      legend: [],
      series: [],
      yAxis: [],
      timeSource: [],
      total: 10,
      chartActive: '',
      chartBtnArr: [],
      myChart: null,
      loading: false,
      csOption: [],
      equipOption: [],
      tableData: [],
      columns: []
    };
  },
  created() {
    window.addEventListener('resize', () => {
      this.getHeight();
      this.getChartData();
    });
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
      // this.getChartData();
      this.getParams();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight, this.getChartData);
  },
  watch: {
    time: function(val) {
      if (val) {
        this.search.startTime = val[0];
        this.search.endTime = val[1];
      } else {
        this.search.startTime = '';
        this.search.endTime = '';
      }
    }
  },
  computed: {
    bcOption() {
      return this.$store.getters.bcOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    cjOption() {
      return this.$store.getters.cjOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    }
  },
  methods: {
    // 下拉框部分
    async getParams(val) {
      const { data } = await getParams1({ gongxu: val });
      let arr = [];
      data.map(item => {
        let obj = Object.assign({}, item);
        obj.label = item.cs_type;
        obj.value = item.cs_type;
        arr.push(obj);
      });
      this.options = arr;
    },
    async getEquip(val) {
      const equipData = await getSysDict(val);
      this.equipOption = equipData.data.dataList;
    },
    async getTableData() {
      let form = Object.assign({}, this.search);
      delete form['params'];
      const res = await getHistoryTrackData(form);
      if (res.code == 1) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    async changeGX(val) {
      this.getParams(val);
      this.search.devSn = [];
      if (val) {
        const res = await getSysDictByName(val + '设备');
        if (res.code == 1) {
          let bh = res.data.dataList[0]['bh'];
          this.getEquip(bh);
        }
      } else {
        this.equipOption = [];
      }
    },
    getHeight() {
      this.tableHeight = this.$refs.chartTable.offsetHeight;
    },
    handleSizeChange(val) {
      this.search.current = 1;
      this.search.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.current = val;
      this.getTableData();
    },
    searchNow() {
      this.$refs['search'].validate((valid, object) => {
        if (valid) {
          // 获取动态的列表表头
          let checked = this.$refs.cascader.getCheckedNodes(true);
          this.chartBtnArr = [];
          let columns = [];
          checked.map(item => {
            if (item.level == 2) {
              this.chartBtnArr.push({ label: item.label, value: item.value });
              let findindex = null;
              let find = columns.find((param, index) => {
                if (param.label == item.parent.value) {
                  findindex = index;
                  return param.label == item.parent.value;
                }
              });
              if (!find) {
                let data = {
                  label: item.parent.value,
                  children: [
                    {
                      label: item.label,
                      value: item.value
                    }
                  ]
                };
                columns.push(data);
              } else {
                columns[findindex]['children'].push({
                  label: item.label,
                  value: item.value
                });
              }
            } else {
              columns.push({
                label: item.label,
                value: item.value
              });
            }
          });
          this.columns = columns;
          this.getTableData();
        } else {
          this.$message({
            message: '请选择工序、参数类型、机台和时间！',
            iconClass: 'el-icon-warning',
            customClass: 'common-message'
          });
          return false;
        }
      });
    },
    groupBy(array, f) {
      let groups = {};
      array.forEach(function(o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function(group) {
        return groups[group];
      });
    },
    arrayGroupBy(list, groupId) {
      let sorted = this.groupBy(list, function(item) {
        return [item[groupId]];
      });
      return sorted;
    },
    llxsFilter(row, col, val) {
      return parseInt(val) / 100;
    }
  }
};
</script>

<style lang="stylus" scoped>
.common-wrapper {
  height: 100%;
}

.common-search {
  display: flex;

  ::v-deep .btn-list .el-form-item__content {
    display: flex;
  }
}
</style>
